<template>
	<div id="app">
		<div id="nav">
			<router-link to="/">Home1</router-link> |
			<router-link to="/about">About</router-link>|
			<router-link :to="`/${prefix}/first-child/home`">FirstChildHome</router-link>|
			<router-link :to="`/${prefix}/first-child/about`">FirstChildAbout</router-link>|
			<router-link :to="`/${prefix}/second-child/home`">SecondChildHome</router-link>|
			<router-link :to="`/${prefix}/second-child/about`">SecondChildAbout</router-link>
		</div>
		<div>
			<micro-app
				v-if="isChild"
				v-bind="micro"
				destory
				@created='created'
				@beforemount='beforemount'
				@mounted='mounted'
				@unmount='unmount'
				@error='error'
				@datachange='handleDataChange'
			></micro-app>
			<router-view v-else></router-view>
		</div>
	</div>
</template>

<script>
import { MICRO_APPS, CHILD_PREFIX } from './micro/config.js'

export default {
	name: 'App',
	data () {
		return {
			isChild: false			/**是否为子模块 */
			, micro: {				
				url: '' 			/**子模块地址 */
				, key: '' 			/**vue 标签的 key 值，用于不同子模块间的切换时，组件重新渲染 */
				, name: '' 			/**子模块名称，唯一 */
				, data: {}			/**子模块数据 */
				, baseroute: ''		/**子模块数据 */
			}
			, prefix: CHILD_PREFIX	/**子模块链接前缀 */
		}
	}
	, watch: {
		$route (val) { /**监听路由变化修改视图显示 */
			this.changeChild(val)
		}
	}
	, created () {
		this.changeChild(this.$route)
	}
	, methods: {
		created () { /**子模块创建 */
			console.log(`${this.micro.name}-created`)
		}
		, beforemount () { /**子模块挂载之前 */
			console.log(`${this.micro.name}-beforemount`)
		}
		, mounted () { /**子模块挂载 */
			this.loading = false
			console.log(`${this.micro.name}-mounted`)
		}
		, unmount () { /**子模块卸载 */
			console.log(`${this.micro.name}-unmount`)
		}
		, error () { /**子模块异常 */
			console.log(`${this.micro.name}-error`)
		}

		, getAppUrl (name) { /**获取子模块 url 和 name */
			return MICRO_APPS.find(app => app.name === name) || {}
		}
		, changeChild (route) { /**修改子视图显示 */
			let path = route.path.toLowerCase()
				, paths = path.split('/')

			/**判断是否为子模块，子模块有固定的前缀，在 micro/config 设置 */
			this.isChild = paths.length > 2 && paths[1] === CHILD_PREFIX

			if (this.isChild) {
				let app = this.getAppUrl(paths[2])

				this.micro = {
					...app
					, data: { name: route.name }
					, key: `${app.name}`
					, baseroute: `/${CHILD_PREFIX}/${paths[2]}`
				}
			}
		}
		, handleDataChange (event) { /**获取子路由传递的信息 */
			let data = event.detail.data
			if(data.route) this.$router.push({ name: data.route.name })
		}
	}
}
</script>

<style>
#app {
	font-family: Avenir, Helvetica, Arial, sans-serif;
	-webkit-font-smoothing: antialiased;
	-moz-osx-font-smoothing: grayscale;
	text-align: center;
	color: #2c3e50;
}

#nav {
	padding: 30px;
}

#nav a {
	font-weight: bold;
	color: #2c3e50;
}

#nav a.router-link-exact-active {
	color: #42b983;
}
</style>
